import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LianBao
 * Date: 2024-09-14
 * Time: 13:04
 */
public class demo1 {
    private static int count = 0;

    private static Object locker = new Object();

    public static void main1(String[] args) throws InterruptedException {
        //解决线程安全问题1:加锁
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                synchronized (locker) {
                    count++;
                }
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                synchronized (locker) {
                    count++;
                }
            }
        });
        t1.start();
        Thread.sleep(1000);
        t2.start();
        System.out.println(count);
    }

    public static void main2(String[] args) throws InterruptedException {
        ReentrantLock lock = new ReentrantLock();

        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                lock.lock();
                count++;
                lock.unlock();
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                lock.lock();
                count++;
                lock.unlock();
            }
        });
        t1.start();
        t2.start();
        Thread.sleep(1000);
        System.out.println(count);
    }

    public static void main(String[] args) throws InterruptedException {

        Semaphore semaphore = new Semaphore(1);//1个资源


        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                try {
                    semaphore.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                count++;
                semaphore.release();
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                try {
                    semaphore.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                count++;
                semaphore.release();
            }
        });
        t1.start();
        t1.join();
        t2.start();
        t2.join();
        System.out.println(count);
    }
}
